package com.lin.service.impl;

import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.json.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lin.config.AlipayConfig;
import com.lin.entity.UserBalance;
import com.lin.mapper.UserBalanceMapper;
import com.lin.service.UserBalanceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 林伟鸿
 * @since 2021-11-24
 */
@Service
public class UserBalanceServiceImpl extends ServiceImpl<UserBalanceMapper, UserBalance> implements UserBalanceService {

    @Autowired
    UserBalanceMapper userBalanceMapper;

    QueryWrapper<UserBalance> queryWrapper;

    /**
     * 对接阿里支付宝沙箱接口
     * @param out_trade_no 交易编号
     * @param subject 订单物品名称
     * @param total_amount 总价
     * @param product_code 商品属性
     * @param userId 用户ID
     * @return
     * @throws AlipayApiException
     */
    @Override
    public String pay(String out_trade_no, String subject, String total_amount, String product_code,String userId) throws AlipayApiException {
        AlipayConfig alipayConfig = new AlipayConfig();
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.URL, alipayConfig.APPID, alipayConfig.RSA_PRIVATE_KEY,alipayConfig.FORMAT,alipayConfig.CHARSET,alipayConfig.ALIPAY_PUBLIC_KEY,alipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
//        model.setBody();
        model.setProductCode(product_code);

        //设置参数
        request.setBizModel(model);
        request.setNotifyUrl(alipayConfig.notify_url);
        request.setReturnUrl(alipayConfig.return_url);

        //生成表单
        String body = alipayClient.pageExecute(request).getBody();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", Integer.parseInt(userId));
        UserBalance userBalance = userBalanceMapper.selectOne(queryWrapper);
        userBalance.setMoney(userBalance.getMoney()+Integer.parseInt(total_amount));
        userBalanceMapper.updateById(userBalance);
//        System.out.println(body);
        return body;
    }
}
